#pragma once

#include <unordered_map>
#include <string>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

static const std::string sep = ": ";

class Dict
{
private:
    void Load(const std::string &path)
    {
        // 打开文件
        std::ifstream in(path);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s failed\n", _path.c_str());
            exit(OPEN_ERROR);
        }

        std::string line;
        while (std::getline(in, line))
        {
            if (line.empty())
                continue;
            //LOG(DEBUG, "Load: %s success\n", line.c_str());

            auto pos = line.find(sep);
            if (pos == std::string::npos)
                continue;

            std::string key = line.substr(0, pos); //     :
            if (key.empty())
                continue;

            std::string value = line.substr(pos + sep.size()); // xxx:
            if (value.empty())
                continue;

            _dict.insert(std::make_pair(key, value));
        }
        LOG(INFO, "load %s sunccess\n", _path.c_str());

        // 关闭文件
        in.close();
    }

public:
    Dict(const std::string &path)
        : _path(path)
    {
        Load(_path);
    }

    std::string translate(std::string &word)
    {
        if (word.empty())
            return "None";
        auto iter = _dict.find(word);
        if (iter == _dict.end())
            return "None";
        return iter->second;
    }

    ~Dict()
    {
    }

private:
    std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};